"""
相关设置界面
"""

import time

import qdarkstyle
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtWidgets
import Simulation
from Remote_Connect import Client
import netaddr  # 用于删除ip地址前导0
from lib import db


class Setting_UI(QDialog, Simulation.Simulation_cfg):
    def __init__(self):
        super().__init__()
        self.Remote_VISSIM = False  # 是否选择远程仿真


        # 远程连接对象
        self.Remote_Client = Client.TcpLogic()

        self.setWindowTitle("参数设置")
        self.setObjectName("UI_Setting")
        self._translate = QtCore.QCoreApplication.translate

        self.left_layout = QVBoxLayout()
        self.right_layout = QVBoxLayout()
        self.all_layout = QHBoxLayout()

        # 数据库连接
        self.GroupBox_1 = QGroupBox('数据库连接')
        self.layout_1 = QVBoxLayout()
        self.layout_1_1 = QHBoxLayout()
        self.layout_1_2 = QHBoxLayout()
        self.layout_1_3 = QHBoxLayout()

        self.label_1_1 = QLabel()  # 数据库名称
        self.lineEdit_1_1 = QLineEdit()  # 数据库名称
        self.label_1_2 = QLabel()  # 用户名
        self.lineEdit_1_2 = QLineEdit()  # 用户名
        self.label_1_3 = QLabel()  # 登录密码
        self.lineEdit_1_3 = QLineEdit()  # 登录密码
        self.lineEdit_1_3.setEchoMode(QLineEdit.Password)  # 设置密码模式

        self.btn_test = QPushButton('测试数据库连接')

        # vissim仿真参数
        self.GroupBox_2 = QGroupBox('vissim仿真参数')
        self.layout_2 = QVBoxLayout()
        self.layout_2_1 = QHBoxLayout()
        self.layout_2_2 = QHBoxLayout()
        self.layout_2_3 = QHBoxLayout()

        self.label_2_1 = QLabel()
        self.lineEdit_2_1 = QSpinBox()  # 仿真总步长
        self.lineEdit_2_1.setSingleStep(100)
        self.lineEdit_2_1.setRange(100, 100000)
        self.label_2_2 = QLabel()
        self.label_2_2_r = QLabel()
        self.lineEdit_2_2 = QDoubleSpinBox()  # 仿真速度（秒/步）
        self.lineEdit_2_2.setSingleStep(0.1)  # 设置最小步长为0.1
        self.lineEdit_2_2.setRange(0.01, 100)  # 设置范围
        self.label_2_3 = QLabel()
        self.label_2_3_r = QLabel()
        self.lineEdit_2_3 = QSpinBox()  # 数据库同步率（每_帧进行同步）
        self.lineEdit_2_3.setSingleStep(1)  # 设置最小步长为0.1
        self.lineEdit_2_3.setRange(1, 100)  # 设置范围

        # UI界面参数
        self.GroupBox_3 = QGroupBox('UI界面参数')
        self.layout_3 = QVBoxLayout()
        self.layout_3_1 = QHBoxLayout()
        self.layout_3_2 = QHBoxLayout()
        self.layout_3_3 = QHBoxLayout()

        self.label_3_1 = QLabel()  # 地图刷新率
        self.label_3_1_r = QLabel()  # 秒/帧
        self.lineEdit_3_1 = QDoubleSpinBox()
        self.lineEdit_3_1.setSingleStep(0.1)  # 设置最小步长为0.1
        self.lineEdit_3_1.setRange(1, 10)  # 设置范围

        self.label_3_2 = QLabel()  # 数据刷新率
        self.label_3_2_r = QLabel()  # 秒/帧
        self.lineEdit_3_2 = QDoubleSpinBox()
        self.lineEdit_3_2.setSingleStep(0.1)  # 设置最小步长为0.1
        self.lineEdit_3_2.setRange(1, 10)  # 设置范围

        self.label_3_3 = QLabel()
        self.lineEdit_3_3 = QLineEdit()

        # vissim连接设置
        self.GroupBox_4 = QGroupBox('vissim连接设置')
        self.label_4_1 = QLabel()  # Vissim连接方式
        self.label_4_2 = QLabel()  # 本地路网文件
        self.label_4_3 = QLabel()  # 服务器ip
        self.label_4_4 = QLabel()  # 服务器端口号

        self.combobox_4_1 = QComboBox()  # 选择连接方式
        self.combobox_4_1.currentIndexChanged.connect(self.combobox_change)  # 切换
        self.lineEdit_4_1 = QLineEdit()  # 本地路网文件
        self.lineEdit_4_1.setEnabled(False)
        self.lineEdit_4_2 = QLineEdit()  # 服务器ip
        self.lineEdit_4_2.setInputMask('000.000.000.000;_')
        self.lineEdit_4_3 = QLineEdit()  # 服务器端口号

        self.btn_load_file = QPushButton('选择路网文件')
        self.btn_connect = QPushButton('测试链接')

        # 进度条
        self.FeatLabel = QLabel('就绪..                   ')
        self.FeatProgressBar = QProgressBar(self)
        self.FeatProgressBar.setMinimum(0)
        self.FeatProgressBar.setMaximum(100)  # 总进程换算为100
        self.FeatProgressBar.setValue(0)  # 进度条初始值为0
        self.FeatLayout = QHBoxLayout()
        self.FeatLayout.addWidget(self.FeatLabel)
        self.FeatLayout.addWidget(self.FeatProgressBar)

        # 暂时隐藏
        self.FeatLabel.hide()
        self.FeatProgressBar.hide()

        # 设置隐藏
        self.lineEdit_4_1.show()  # 本地路网文件
        self.lineEdit_4_2.hide()  # 服务器ip
        self.lineEdit_4_3.hide()  # 服务器端口号
        self.btn_load_file.show()  # 选择路网文件
        self.btn_connect.hide()  # 测试链接
        self.label_4_2.show()  # 本地路网文件
        self.label_4_3.hide()  # 服务器ip
        self.label_4_4.hide()  # 服务器端口号

        self.layout_4 = QVBoxLayout()
        self.layout_4_1 = QHBoxLayout()
        self.layout_4_2 = QHBoxLayout()
        self.layout_4_3 = QHBoxLayout()
        self.layout_4_4 = QHBoxLayout()

        # 确认与取消
        self.layout_set = QHBoxLayout()
        self.btn_set = QPushButton("确认修改")
        self.btn_causal = QPushButton("取消修改")

        self.set_layout()  # 设置布局
        self.UI_translate()  # 设置文字
        self.init_show()  # 初始显示
        self.connect()  # 函数连接

    def set_layout(self):
        self.layout_1_1.addWidget(self.label_1_1)
        self.layout_1_1.addWidget(self.lineEdit_1_1)
        self.layout_1_2.addWidget(self.label_1_2)
        self.layout_1_2.addWidget(self.lineEdit_1_2)
        self.layout_1_3.addWidget(self.label_1_3)
        self.layout_1_3.addWidget(self.lineEdit_1_3)

        self.layout_1.addItem(self.layout_1_1)
        self.layout_1.addItem(self.layout_1_2)
        self.layout_1.addItem(self.layout_1_3)
        self.layout_1.addWidget(self.btn_test)

        self.GroupBox_1.setLayout(self.layout_1)

        self.left_layout.addWidget(self.GroupBox_1)

        # vissim仿真参数
        self.layout_2_1.addWidget(self.label_2_1)
        self.layout_2_1.addWidget(self.lineEdit_2_1)
        self.layout_2_2.addWidget(self.label_2_2)
        self.layout_2_2.addWidget(self.lineEdit_2_2)
        self.layout_2_2.addWidget(self.label_2_2_r)
        self.layout_2_3.addWidget(self.label_2_3)
        self.layout_2_3.addWidget(self.lineEdit_2_3)
        self.layout_2_3.addWidget(self.label_2_3_r)

        self.layout_2.addItem(self.layout_2_1)
        self.layout_2.addItem(self.layout_2_2)
        self.layout_2.addItem(self.layout_2_3)

        self.GroupBox_2.setLayout(self.layout_2)

        self.right_layout.addWidget(self.GroupBox_2)

        # UI界面参数
        self.layout_3_1.addWidget(self.label_3_1)  # 地图刷新率
        self.layout_3_1.addWidget(self.lineEdit_3_1)  # 地图刷新率
        self.layout_3_1.addWidget(self.label_3_1_r)  # 地图刷新率
        self.layout_3_2.addWidget(self.label_3_2)  # 表格刷新率
        self.layout_3_2.addWidget(self.lineEdit_3_2)  # 表格刷新率
        self.layout_3_2.addWidget(self.label_3_2_r)  # 表格刷新率
        # self.layout_3_3.addWidget(self.label_3_3)
        # self.layout_3_3.addWidget(self.lineEdit_3_3)

        self.layout_3.addItem(self.layout_3_1)
        self.layout_3.addItem(self.layout_3_2)
        self.layout_3.addItem(self.layout_3_3)

        self.GroupBox_3.setLayout(self.layout_3)

        # Vissim连接方式
        self.layout_4_1.addWidget(self.label_4_1)  # 选择Vissim连接方式
        self.layout_4_1.addWidget(self.combobox_4_1)  # 选择Vissim连接方式
        self.layout_4_2.addWidget(self.label_4_2)  # 本地路网文件
        self.layout_4_2.addWidget(self.lineEdit_4_1)  # 本地路网文件
        self.layout_4_3.addWidget(self.label_4_3)  # 服务器ip
        self.layout_4_3.addWidget(self.lineEdit_4_2)  # 服务器ip
        self.layout_4_4.addWidget(self.label_4_4)  # 服务器端口号
        self.layout_4_4.addWidget(self.lineEdit_4_3)  # 服务器端口号

        self.layout_4.addItem(self.layout_4_1)
        self.layout_4.addItem(self.layout_4_2)
        self.layout_4.addItem(self.layout_4_3)
        self.layout_4.addItem(self.layout_4_4)
        self.layout_4.addWidget(self.btn_load_file)  # 加载路网文件
        self.layout_4.addWidget(self.btn_connect)  # 测试连接

        self.GroupBox_4.setLayout(self.layout_4)

        # 确认与取消
        self.layout_set.addWidget(self.btn_set)
        self.layout_set.addWidget(self.btn_causal)

        # all
        self.right_layout.addWidget(self.GroupBox_2)
        self.left_layout.addWidget(self.GroupBox_3)
        self.right_layout.addWidget(self.GroupBox_4)
        self.right_layout.addItem(self.layout_set)

        self.all_layout.addItem(self.left_layout)
        self.all_layout.addItem(self.right_layout)

        self.layout_V = QVBoxLayout()
        self.layout_V.addItem(self.all_layout)
        self.layout_V.addItem(self.FeatLayout)
        self.setLayout(self.layout_V)

    def UI_translate(self):
        self.label_1_1.setText(self._translate("UI_Setting", "数据库名称："))
        self.label_1_2.setText(self._translate("UI_Setting", "用户名："))
        self.label_1_3.setText(self._translate("UI_Setting", "登陆密码："))
        self.label_2_1.setText(self._translate("UI_Setting", "仿真步长：      "))
        self.label_2_2.setText(self._translate("UI_Setting", "仿真速度：      "))
        self.label_2_3.setText(self._translate("UI_Setting", "数据库同步速率："))
        self.label_2_2_r.setText(self._translate("UI_Setting", " 秒/帧"))
        self.label_2_3_r.setText(self._translate("UI_Setting", " 帧同步"))

        self.label_3_1.setText(self._translate("UI_Setting", "地图刷新率：     "))
        self.label_3_2.setText(self._translate("UI_Setting", "数据刷新率：     "))
        self.label_3_1_r.setText(self._translate("UI_Setting", " 秒/帧"))
        self.label_3_2_r.setText(self._translate("UI_Setting", " 秒/帧"))

        self.label_4_1.setText(self._translate("UI_Setting", "Vissim连接方式："))
        self.label_4_2.setText(self._translate("UI_Setting", "本地路网文件：  "))
        self.label_4_3.setText(self._translate("UI_Setting", "服务器ip：      "))
        self.label_4_4.setText(self._translate("UI_Setting", "服务器端口号：  "))
        self.combobox_4_1.addItem('本地Vissim仿真')
        self.combobox_4_1.addItem('远程Vissim仿真')

    def combobox_change(self):
        if self.combobox_4_1.currentIndex() == 0:
            # 本地：
            # 设置隐藏
            self.lineEdit_4_1.show()  # 本地路网文件
            self.lineEdit_4_2.hide()  # 服务器ip
            self.lineEdit_4_3.hide()  # 服务器端口号
            self.btn_load_file.show()  # 选择路网文件
            self.btn_connect.hide()  # 测试链接
            self.label_4_2.show()  # 本地路网文件
            self.label_4_3.hide()  # 服务器ip
            self.label_4_4.hide()  # 服务器端口号
        elif self.combobox_4_1.currentIndex() == 1:
            # 远程
            # 设置隐藏
            self.lineEdit_4_1.hide()  # 本地路网文件
            self.lineEdit_4_2.show()  # 服务器ip
            self.lineEdit_4_3.show()  # 服务器端口号
            self.btn_load_file.hide()  # 选择路网文件
            self.btn_connect.show()  # 测试链接
            self.label_4_2.hide()  # 本地路网文件
            self.label_4_3.show()  # 服务器ip
            self.label_4_4.show()  # 服务器端口号

    def init_show(self):
        self.lineEdit_1_1.setText(self.Flag_db_port)  # 数据库
        self.lineEdit_1_2.setText(self.Flag_db_user)  # 用户名
        self.lineEdit_1_3.setText(self.Flag_db_password)  # 登录密码
        self.lineEdit_2_1.setValue(self.Flag_vis_step)  # Vissim仿真总步长
        self.lineEdit_2_2.setValue(self.Flag_vis_step_time)  # vissim仿真速度
        self.lineEdit_2_3.setValue(self.Flag_vis_update_step)  # Vissim数据库更新速度
        self.lineEdit_3_1.setValue(self.Flag_map_update_time)  # UI地图更新速度
        self.lineEdit_3_2.setValue(self.Flag_table_update_time)  # UI表格更新速度

        self.lineEdit_4_1.setText(self.Flag_Vissim_Road)  # 设置路网名

    def connect(self):
        self.btn_connect.clicked.connect(self.On_TestRemoteConnect_Clicked)
        self.btn_test.clicked.connect(self.On_TestDBConnect_Clicked)
        self.btn_set.clicked.connect(self.On_Write_Clicked)
        self.btn_causal.clicked.connect(self.init_show)
        self.btn_load_file.clicked.connect(self.On_VissimRoad_Clicked)

    def On_TestRemoteConnect_Clicked(self):

        ip = str(self.lineEdit_4_2.text())
        # 删除ip地址前导0
        try:
            self.Remote_ip = netaddr.IPAddress(ip, flags=netaddr.ZEROFILL).ipv4()
        except:
            QMessageBox.information(self, "information", "ip地址格式错误!", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            return

        self.Remote_port = int(self.lineEdit_4_3.text())
        self.Remote_Client.aim_ip = self.Remote_ip
        self.Remote_Client.aim_port = self.Remote_port
        self.Remote_Client.Remote_test = False
        # self.FeatLabel = QLabel('测试VISSIM远程连接..      ')
        try:
            self.Remote_Client.tcp_client_start()
            msg = {'TYPE': 'test'}
            self.Remote_Client.tcp_send(mess=msg)
            time.sleep(3)
            self.Remote_Client.tcp_close()
        except:
            pass
        if self.Remote_Client.Remote_test:
            QMessageBox.information(self, "information", "测试连接成功!", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            self.Remote_Client.Remote_test = False
        else:
            QMessageBox.information(self, "information", "连接失败，请检查目标服务器地址；\n是否有网络连接；或确认服务端是否开启!",
                                    QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)

    def On_TestDBConnect_Clicked(self):
        test_db = db.database()
        test_db.Flag_db_port = str(self.lineEdit_1_1.text())
        test_db.Flag_db_user = str(self.lineEdit_1_2.text())
        test_db.Flag_db_password = str(self.lineEdit_1_3.text())
        try:
            test_db.Create_conn()
        except:
            QMessageBox.information(self, "information", "连接失败，请检查目标数据库地址；\n是否有网络连接；或确认用户名与密码!",
                                    QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            return
        else:
            QMessageBox.information(self, "information", "测试数据库连接成功!", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)

    def On_Write_Clicked(self):

        test_db = db.database()
        test_db.Flag_db_port = str(self.lineEdit_1_1.text())
        test_db.Flag_db_user = str(self.lineEdit_1_2.text())
        test_db.Flag_db_password = str(self.lineEdit_1_3.text())
        try:
            test_db.Create_conn()
        except:
            QMessageBox.information(self, "information", "数据库测试连接失败，请检查目标数据库地址；\n是否有网络连接；或确认用户名与密码!",
                                    QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            return

        self.Flag_db_port = str(self.lineEdit_1_1.text())  # database
        self.Flag_db_user = str(self.lineEdit_1_2.text())  # user
        self.Flag_db_password = str(self.lineEdit_1_3.text())  # password
        self.Flag_vis_step = int(self.lineEdit_2_1.text())  # Vissim仿真总步长
        self.Flag_vis_step_time = float(self.lineEdit_2_2.text())  # vissim仿真速度
        self.Flag_vis_update_step = int(self.lineEdit_2_3.text())  # Vissim数据库更新速度
        self.Flag_map_update_time = float(self.lineEdit_3_1.text())  # UI地图更新速度
        self.Flag_table_update_time = float(self.lineEdit_3_2.text())  # UI表格更新速度
        self.Flag_Vissim_Road = str(self.lineEdit_4_1.text())  # 更改路网文件（可能会报错）

        if self.combobox_4_1.currentIndex() == 0:
            self.Remote_VISSIM = False

        if self.combobox_4_1.currentIndex() == 1:
            ip = str(self.lineEdit_4_2.text())
            # 删除ip地址前导0
            try:
                self.Remote_ip = netaddr.IPAddress(ip, flags=netaddr.ZEROFILL).ipv4()
            except:
                QMessageBox.information(self, "information", "ip地址格式错误!", QMessageBox.Yes | QMessageBox.No,
                                        QMessageBox.Yes)
                return

            self.Remote_port = int(self.lineEdit_4_3.text())
            self.Remote_Client.aim_ip = self.Remote_ip
            self.Remote_Client.aim_port = self.Remote_port
            self.Remote_Client.Remote_test = False
            # self.FeatLabel = QLabel('测试VISSIM远程连接..      ')
            try:
                self.Remote_Client.tcp_client_start()
                msg = {'TYPE': 'test'}
                self.Remote_Client.tcp_send(mess=msg)
                time.sleep(3)
                self.Remote_Client.tcp_close()
            except:
                pass
            if self.Remote_Client.Remote_test:

                QMessageBox.information(self, "information", "参数修改成功!", QMessageBox.Yes | QMessageBox.No,
                                        QMessageBox.Yes)

                self.Remote_Client.Remote_test = False
                self.Remote_VISSIM = True

            else:
                QMessageBox.information(self, "information", "连接失败，请检查目标服务器地址；\n是否有网络连接；或确认服务端是否开启!",
                                        QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)





    def On_VissimRoad_Clicked(self):
        directory = QtWidgets.QFileDialog.getOpenFileName(self, "getOpenFileName", "./", "Vissim Road(*.inp)")
        self.lineEdit_4_1.setText(directory[0])

